package cn.gcjxsc.service.common;

import cn.gcjxsc.consts.ErrorType;
import cn.gcjxsc.entity.common.DbErrorRecord;
import cn.gcjxsc.repository.common.DbErrorRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author pumbaa
 * @since 1.0
 */
@Service
public class ErrorService {
    @Autowired
    private DbErrorRecordRepository errorRecordRepository;

    @Transactional
    public void save(DbErrorRecord record) {
        errorRecordRepository.save(record);
    }

    @Transactional
    public void recordError(Exception e, ErrorType errorType) {
        DbErrorRecord record = new DbErrorRecord();
        record.setCreated(System.currentTimeMillis() / 1000);
        record.setErrorMsg(e.getMessage());
        record.setErrorType(errorType);
        record.setTrace(recordTrace(e));
        record.setSummary(errorType.getDesc());
        save(record);
    }

    public String recordTrace(Exception e) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        return stringWriter.toString();
    }
}
